'''
Created on 2016年2月22日

@author: Administrator
'''
from asyncore import dispatcher
from asynchat import async_chat
import asyncore, socket

PORT = 5005
NAME = 'ChatRoom'

class ChatSession(async_chat):
    def __init__(self, server, sock):
        async_chat.__init__(self, sock)
        self.server = server
        self.set_terminator(b'\r\n')
        self.data = []
        self.push(('Welcome to %s\r\n' % self.server.name).encode('utf-8', 'ignore'))
        
    def collect_incoming_data(self, data):
        self.data.append(data.decode('utf-8', 'ignore'))
        
    def found_terminator(self):
        line = ''.join(self.data)
        self.data = []
        self.server.broadcast(line)
        
    def handle_close(self):
        async_chat.handle_close(self)
        self.server.disconncet(self)

class ChatServer(dispatcher):
    def __init__(self, port, name):
        dispatcher.__init__(self)
        self.name = name
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind(('', port))
        self.listen(5)
        self.sessions = []
        
    def disconncet(self, session):
        self.sessions.remove(session)
        
    def broadcast(self, line):
        for session in self.sessions:
            session.push((line + '\r\n').encode('utf-8', 'ignore'))
            
    def handle_accept(self):
        conn, addr = self.accept()
        self.sessions.append(ChatSession(self, conn))
        print('connection attempt from ', addr[0])
        

if __name__ == '__main__':
    s = ChatServer(PORT, NAME)
    try: asyncore.loop()
    except KeyboardInterrupt: print